<template>
  <Dialog class="myDig" :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入产品名称" />
      </el-form-item>
      <el-form-item label="产品规格" prop="specs">
        <el-input v-model="formData.specs" placeholder="请输入产品规格" />
      </el-form-item>
      <el-form-item label="产品型号" prop="type">
        <el-input v-model="formData.type" placeholder="请输入产品型号" />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="formData.unit" placeholder="请输入单位" />
      </el-form-item>
      <el-form-item label="成本最低价格(元)" prop="costMinPrice">
        <el-input v-model="formData.costMinPrice" step="0.01" type="number" placeholder="请输入成本最低价格(元)" />
      </el-form-item>
      <el-form-item label="成本最高价格(元)" prop="costMaxPrice">
        <el-input v-model="formData.costMaxPrice" step="0.01" type="number" placeholder="请输入成本最高价格(元)" />
      </el-form-item>
      <el-form-item label="建议最低售价(元)" prop="suggestedMinPrice">
        <el-input v-model="formData.suggestedMinPrice" step="0.01" type="number" placeholder="请输入建议最低售价(元)" />
      </el-form-item>
      <el-form-item label="建议最高售价(元)" prop="suggestedMaxPrice">
        <el-input v-model="formData.suggestedMaxPrice" step="0.01" type="number" placeholder="请输入建议最高售价(元)" />
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-input v-model="formData.status" placeholder="请输入状态" />
      </el-form-item> -->
      <el-form-item label="产品分类" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择产品分类">
          <el-option v-if="ProductCategoryList.length == 0" label="请选择字典生成" value="1" />
          <el-option v-show="ProductCategoryList.length > 0" v-for="(item, index) in ProductCategoryList " :key="index"
            :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品品牌" prop="brandId">
        <el-select v-model="formData.brandId" placeholder="请选择产品品牌">
          <el-option v-if="ProductBrandList.length == 0" label="请选择字典生成" value="" />
          <el-option v-show="ProductBrandList.length > 0" v-for="(item, index) in ProductBrandList " :key="index"
            :label="item.name" :value="item.id"> </el-option>

        </el-select>
      </el-form-item>
      <el-form-item label="产品供应商" prop="supplierId">
        <el-select v-model="formData.supplierId" placeholder="请选择产品供应商">
          <el-option v-if="ProductSupplierList.length == 0" label="请选择字典生成" value="" />
          <el-option v-show="ProductSupplierList.length > 0" v-for="(item, index) in ProductSupplierList " :key="index"
            :label="item.name" :value="item.id"> </el-option>

        </el-select>
      </el-form-item>
      <el-form-item label="产品描述" prop="description">
        <!-- <el-input v-model="formData.description" placeholder="请输入产品供应商编号" /> -->
        <Editor v-model="formData.description" height="301px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/quote/product'
import { ProductSupplierApi } from '@/api/quote/ProductSupplier'
import { ProductCategoryApi } from '@/api/quote/ProductCategory'
import { ProductBrandApi } from '@/api/quote/productBrand'

/** 标准品 表单 */
defineOptions({ name: 'ProductForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  specs: undefined,
  type: undefined,
  unit: undefined,
  costMinPrice: undefined,
  costMaxPrice: undefined,
  suggestedMinPrice: undefined,
  suggestedMaxPrice: undefined,
  status: undefined,
  categoryId: undefined,
  brandId: undefined,
  supplierId: undefined,
  description: undefined
})
const ProductSupplierList = ref([])
const ProductCategoryList = ref([])
const ProductBrandList = ref([])
const formRules = reactive({
  name: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  specs: [{ required: true, message: '产品规格不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '产品型号不能为空', trigger: 'blur' }],
  costMinPrice: [{ required: true, message: '成本最低价格(元)不能为空', trigger: 'blur' }],
  suggestedMinPrice: [{ required: true, message: '建议最低售价(元)不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '产品分类编号不能为空', trigger: 'blur' }],
  brandId: [{ required: true, message: '产品品牌编号不能为空', trigger: 'blur' }],
  supplierId: [{ required: true, message: '产品供应商编号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const getAllSelectOption = async () => {
  const params = {
    pageNo: 1,
    pageSize: 100
  }
  const res = await Promise.all([ProductSupplierApi.getProductSupplierPage(params), ProductCategoryApi.getProductCategoryList({}), ProductBrandApi.getProductBrandPage(params)])
  if (res.length == 3) {
    ProductSupplierList.value = res[0].list
    ProductCategoryList.value = res[1]
    ProductBrandList.value = res[2].list
  } else {
    message.error('获取下拉选项失败')
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  getAllSelectOption()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductApi.getProduct(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  // console.log(formRef.value)
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProductVO
    if (formType.value === 'create') {
      if (!data.description) {
        data.description = `<p>暂无</p>`
      }
      await ProductApi.createProduct(data)
      message.success(t('common.createSuccess'))
    } else {
      if (!data.description) {
        data.description = `<p>暂无</p>`
      }
      await ProductApi.updateProduct(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    specs: undefined,
    type: undefined,
    unit: undefined,
    costMinPrice: undefined,
    costMaxPrice: undefined,
    suggestedMinPrice: undefined,
    suggestedMaxPrice: undefined,
    status: undefined,
    categoryId: undefined,
    brandId: undefined,
    supplierId: undefined,
    description: undefined
  }
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss">
.myDig {
  .el-form {
    :deep(.el-form-item) {
      label {
        width: 175px !important;
        text-align: center;
        display: block;
      }

      &:last-of-type {
        .el-form-item__label {
          width: 175px !important;
          text-align: center;
          display: block;
        }
      }
    }
  }
}
</style>
